package com.ctsi.security.event;

import com.ctsi.commons.event.AbstractObserver;
import com.ctsi.commons.event.BaseEvent;
import com.ctsi.framework.common.startrun.ComponentFactory;
import com.ctsi.oauth.config.RedisTokenStorePatched;
import com.ctsi.organise.common.api.OrganiseFactoryBean;
import com.ctsi.organise.common.model.UserLogin;
import com.ctsi.security.manager.impl.SecurityImpl;
import org.springframework.security.oauth2.common.OAuth2AccessToken;

import java.util.Collection;
import java.util.List;
import java.util.Map;


/**
 * @author gbk
 * 
 * 更新用户和角色的缓存
 */
@SuppressWarnings("unchecked")
public class UpdCacheUserRoles extends AbstractObserver {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -807064399290909311L;
	
	private static org.slf4j.Logger logger=org.slf4j.LoggerFactory.getLogger(UpdCacheUserRoles.class);
	
	@Override
	public void onEvent(Object[] args) {
		BaseEvent be=(BaseEvent)args[0];
		Map<String,Object> map=(Map<String,Object>)be.getContext();
		List<String> listUserLoginId=(List<String>)map.get("listUserLoginId");
		this.UpdCache(listUserLoginId);
	}
	//更新缓存
	public void UpdCache(List<String> listUserLoginId){
			for(String userLoginId:listUserLoginId){
				logger.info("更新用户的角色缓存，当前用户：{}",userLoginId);
				RedisTokenStorePatched store = (RedisTokenStorePatched) ComponentFactory.getBean("redisTokenStore");
				if (store != null) {
					UserLogin userLogin = OrganiseFactoryBean.getInstance().getUserLoginProxy().findById(userLoginId);
					Collection<OAuth2AccessToken> tokens = store.findTokensByClientIdAndUserName("webapp",userLogin.getLoginName());
					tokens.stream().forEach(oAuth2AccessToken -> store.removeAccessToken(oAuth2AccessToken));
				}
				SecurityImpl.removeCacheUserRoles(userLoginId);
			}	
	}
}
